package com.mnotice.message.informer.impl;


import com.mnotice.common.constants.InformerEnum;
import com.mnotice.common.entity.message.Notification;
import com.mnotice.message.informer.AbstractInformer;
import com.mnotice.message.informer.JsonFormat;
import com.mnotice.message.service.EmailService;
import freemarker.template.Template;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class EmailInformer extends AbstractInformer {
    @Resource
    private FreeMarkerConfigurer configurer;
    @Resource
    private EmailService emailService;

    public EmailInformer() {
        this.setName(InformerEnum.Email.getMethod());
    }

    public EmailInformer(String name) {
        super(name);
    }

    @Override
    public void informDirect(Notification notification) throws Exception {
        String id = notification.getProjectId() + "_" + notification.getTemplateName();
        Template template = configurer.getConfiguration().getTemplate(id);
        Map<String, Object> model = new HashMap<>();
        JsonFormat format = new JsonFormat(notification.getContent());
        model.put("format", format);
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        emailService.sendEmail(html,notification);
        System.out.println("email notification html = " + html);
    }

    @Override
    public void processFailed(Notification notification) throws Exception {
        throw new Exception();
    }
}
